import numpy as np
import matplotlib.pyplot as plt
import math

def cnvs_pure_shannon_entropy_corrected(I_G, I_0, lambda_factor=2, trials=2000):
    """
    CNVS Thermodynamic Simulator based on pure Shannon Entropy.
    No heuristics. No inferential contagion (rho_c = 0).
    Only physical probability and brute-force information theory.
    """
    M_fragments = math.ceil(I_G / I_0)

    pool_nodi = np.repeat(np.arange(M_fragments), lambda_factor)
    N_total = len(pool_nodi)

    q_values = np.linspace(0.01, 0.99, 100)
    p_success = []

    for q in q_values:
        wins = 0
        k_captured = int(round(q * N_total))

        for _ in range(trials):
            captured_nodes = np.random.choice(pool_nodi, size=k_captured, replace=False)

            unique_captured = len(np.unique(captured_nodes))
            missing_fragments = M_fragments - unique_captured

            H_res = missing_fragments * I_0
            p_guess = 0.0 if H_res > 1024 else 2.0 ** (-H_res)

            if missing_fragments == 0:
                wins += 1
            else:
                if np.random.random() < p_guess:
                    wins += 1

        p_success.append(wins / trials)

    return q_values, p_success, M_fragments


plt.figure(figsize=(11, 7))
np.random.seed(20260525)

scenarios = [
    {"I_0": 100, "color": "red", "label": "Low granularity (I_0 = 100 bits)"},
    {"I_0": 50, "color": "orange", "label": "Medium granularity (I_0 = 50 bits)"},
    {"I_0": 20, "color": "blue", "label": "High granularity (I_0 = 20 bits)"},
    {"I_0": 5, "color": "green", "label": "CNVS Pulverization (I_0 = 5 bits)"}
]

print("Running Pure Shannon Entropy Test...")

for sc in scenarios:
    q_vals, p_vals, M_calc = cnvs_pure_shannon_entropy_corrected(
        I_G=1000,
        I_0=sc["I_0"],
        lambda_factor=2
    )

    plt.plot(
        q_vals,
        p_vals,
        color=sc["color"],
        linewidth=2.5,
        label=f'{sc["label"]} -> {M_calc} fragments'
    )

plt.axvline(x=1/3, color="black", linestyle="--", alpha=0.7, label="BFT Limit (1/3)")

plt.title("CNVS Test 5: Thermodynamic Limit of Shannon Entropy (I_G=1000, λ=2)", fontsize=14, fontweight="bold")
plt.xlabel("Fraction of Physically Corrupted Nodes (q)", fontsize=12)
plt.ylabel("Probability of Total Reconstruction (False Positive)", fontsize=12)
plt.legend(loc="upper left", fontsize=11)
plt.grid(True, linestyle=":", alpha=0.7)

plt.tight_layout()
plt.savefig("CNVS_Test_5_Shannon_Limit.png", dpi=200)
plt.show()

print("Execution complete. Shannon-entropy reconstruction test completed.")